package com.shiduai.mobile.lawyer.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.graphics.drawable.BitmapDrawable


import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.FrameLayout
import androidx.annotation.ColorRes
import androidx.annotation.Nullable
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import java.util.*

class BottomBar(context: Context, @Nullable attr: AttributeSet) : FrameLayout(context, attr) {
    private val fragmentClassList = ArrayList<Class<*>>()
    private val titleList = ArrayList<String>()
    private val iconResBeforeList = ArrayList<Int>()
    private val iconResAfterList = ArrayList<Int>()
    private val fragmentList = ArrayList<Fragment>()
    private var itemCount: Int = 0
    private val paint = Paint()
    private val iconBitmapBeforeList = ArrayList<Bitmap>()
    private val iconBitmapAfterList = ArrayList<Bitmap>()
    private val iconRectList = ArrayList<Rect>()

    private var currentCheckedIndex: Int = 0
    private var firstCheckedIndex: Int = 0

    private var titleColorBefore = Color.parseColor("#999999")
    private var titleColorAfter = Color.parseColor("#ff5d5e")

    var titleSizeInDp = 10
    var iconWidth = 20
    var iconHeight = 20
    var titleIconMargin = 5
    var containerId = 0
    var isHideText = false

    fun setTitleBeforeAndAfterColor(beforeResCode: String, AfterResCode: String) {//支持"#333333"这种形式
        titleColorBefore = Color.parseColor(beforeResCode)
        titleColorAfter = Color.parseColor(AfterResCode)
    }

    fun setTitleBeforeAndAfterColor(@ColorRes beforeRes: Int, @ColorRes afterRes: Int) {//支持"#333333"这种形式
        titleColorBefore = resources.getColor(beforeRes)
        titleColorAfter = resources.getColor(afterRes)
    }

    fun addItem(fragmentClass: Class<*>, title: String, iconResBefore: Int, iconResAfter: Int) {
        fragmentClassList.add(fragmentClass)
        titleList.add(title)
        iconResBeforeList.add(iconResBefore)
        iconResAfterList.add(iconResAfter)
    }

    fun build() {
        itemCount = fragmentClassList.size
        //预创建bitmap的Rect并缓存
        //预创建icon的Rect并缓存
        for (i in fragmentClassList.indices) {
            val beforeBitmap = getBitmap(iconResBeforeList[i])
            iconBitmapBeforeList.add(beforeBitmap)

            val afterBitmap = getBitmap(iconResAfterList[i])
            iconBitmapAfterList.add(afterBitmap)

            val rect = Rect()
            iconRectList.add(rect)

            val clx = fragmentClassList[i]
            try {
                val fragment = clx.newInstance() as Fragment
                fragmentList.add(fragment)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        currentCheckedIndex = firstCheckedIndex
        switchFragment(currentCheckedIndex)
    }

    private fun getBitmap(resId: Int): Bitmap {
        val bitmapDrawable = context.resources.getDrawable(resId) as BitmapDrawable
        return bitmapDrawable.bitmap
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        initParam()
    }

    private var titleBaseLine: Int = 0
    private val titleXList = ArrayList<Int>()

    private var parentItemWidth: Int = 0

    private fun initParam() {
        if (itemCount != 0) {
            //单个item宽高
            parentItemWidth = (getWidth() - getPaddingLeft() - getPaddingRight()) / itemCount
            val parentItemHeight = getHeight()

            //图标边长
            val iconWidth = dp2px(this.iconWidth.toFloat())//先指定20dp
            val iconHeight = dp2px(this.iconHeight.toFloat())

            //图标文字margin
            val textIconMargin = dp2px(titleIconMargin.toFloat() / 2)//先指定5dp，这里除以一半才是正常的margin，不知道为啥，可能是图片的原因

            //标题高度
            val titleSize = dp2px(titleSizeInDp.toFloat())//这里先指定10dp
            paint.textSize = titleSize.toFloat()
            val rect = Rect()
            paint.getTextBounds(titleList[0], 0, titleList[0].length, rect)
            val titleHeight = rect.height()

            //从而计算得出图标的起始top坐标、文本的baseLine
            val textHeight = if (isHideText) 0 else textIconMargin + titleHeight
            val iconTop = (parentItemHeight - iconHeight - textHeight) / 2
            titleBaseLine = parentItemHeight - iconTop

            //对icon的rect的参数进行赋值
            val firstRectX = (parentItemWidth - iconWidth) / 2 + getPaddingLeft()//第一个icon的左
            for (i in 0 until itemCount) {
                val rectX = i * parentItemWidth + firstRectX
                with(iconRectList[i]) {
                    left = rectX
                    top = iconTop
                    right = rectX + iconWidth
                    bottom = iconTop + iconHeight
                }
            }
            //标题（单位是个问题）
            for (i in 0 until itemCount) {
                val title = titleList[i]
                paint.getTextBounds(title, 0, title.length, rect)
                titleXList.add((parentItemWidth - rect.width()) / 2 + parentItemWidth * i + getPaddingLeft())
            }
        }
    }

    private fun dp2px(dpValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)//这里让view自身替我们画背景 如果指定的话
        if (itemCount != 0) {
            //画背景
            paint.isAntiAlias = false
            for (i in 0 until itemCount) {
                var bitmap: Bitmap? = if (i == currentCheckedIndex)
                    iconBitmapAfterList[i]
                else
                    iconBitmapBeforeList[i]
                val rect = iconRectList[i]
                canvas.drawBitmap(bitmap, null, rect, paint)//null代表bitmap全部画出
            }
            //画文字
            if (!isHideText) {
                paint.isAntiAlias = true
                for (i in 0 until itemCount) {
                    val title = titleList[i]
                    paint.color = if (i == currentCheckedIndex) titleColorAfter else titleColorBefore
                    val x = titleXList[i]
                    canvas.drawText(title, x.toFloat(), titleBaseLine.toFloat(), paint)
                }
            }
        }
    }

    private var target = -1
    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> target = withinWhichArea(event.x.toInt())
            MotionEvent.ACTION_UP -> {
                if (event.y >= 0) {
                    if (target == withinWhichArea(event.x.toInt())) {
                        //这里触发点击事件
                        switchFragment(target)
                        currentCheckedIndex = target
                        invalidate()
                    }
                    target = -1
                }
            }
        }
        return true
    }

    private fun withinWhichArea(x: Int): Int {
        return x / parentItemWidth
    }//从0开始

    private var currentFragment: Fragment? = null

    //注意 这里是只支持AppCompatActivity 需要支持其他老版的 自行修改
    fun switchFragment(whichFragment: Int) {
        val fragment = fragmentList[whichFragment]
        val frameLayoutId = containerId

        if (fragment != null) {
            with((context as AppCompatActivity).supportFragmentManager.beginTransaction()) {
                if (fragment.isAdded)
                    if (currentFragment != null) hide(currentFragment!!).show(fragment)
                    else show(fragment)
                else
                    if (currentFragment != null) hide(currentFragment!!).add(frameLayoutId, fragment)
                    else add(frameLayoutId, fragment)
                currentFragment = fragment
                commit()
            }
        }
    }
}